<template>
  <el-upload
    :action="uploadUrl"
    v-model:file-list="fileList"
    :limit="limit"
    :multiple="multiple"
    :show-file-list="true"
    :on-success="handleSuccess"
    list-type="picture-card"
  >
    <el-icon><Plus /></el-icon>
  </el-upload>
</template>

<script setup>
import { ref, watch, defineProps, defineEmits, nextTick } from 'vue';
import { ElMessage } from 'element-plus';
import { Plus } from '@element-plus/icons-vue';

const props = defineProps({
  modelValue: Array,
  limit: { type: Number, default: 1 },
  multiple: { type: Boolean, default: false },
  uploadUrl: { type: String, default: 'http://121.43.176.9:8090/api/oss/upload-image' }
});
const emit = defineEmits(['update:modelValue']);
const fileList = ref([]);
const isUpdatingFromProps = ref(false);

// 外部传入字符串数组时做回显
watch(
  () => props.modelValue,
  (val) => {
    if (isUpdatingFromProps.value) return;
    
    if (val && val.length > 0) {
      // 如果是字符串数组（url），做回显
      if (typeof val[0] === 'string') {
        fileList.value = val.map(url => ({ name: url, url, status: 'success' }));
      } else {
        // 否则直接赋值（fileList），补充 status 字段
        fileList.value = val.map(file => ({ ...file, status: file.status || 'success' }));
      }
    } else {
      fileList.value = [];
    }
  },
  { immediate: true }
);

// 双向绑定fileList，外部可拿到完整fileList（含raw: File）
watch(
  fileList,
  async (val) => {
    if (isUpdatingFromProps.value) return;
    
    isUpdatingFromProps.value = true;
    emit('update:modelValue', val);
    
    // 使用 nextTick 确保在下一个事件循环中重置标志
    await nextTick();
    isUpdatingFromProps.value = false;
  },
  { deep: true }
);

function handleSuccess(res, file, fileListArr) {
  if (res.code === 200 && res.data) {
    // 上传成功后，设置file.url，fileList会自动更新
    file.url = res.data;
  } else {
    ElMessage.error(res.msg || '上传失败');
  }
}
</script>  

<style scoped>
.el-upload-list__item-delete {
  display: block !important;
  opacity: 1 !important;
}
</style> 
  